import UIKit
/**
    B站：https://www.bilibili.com/video/BV144411C7Gg?p=42

    第42课
        1. 循环强引用
        2. 弱引用weak

 */

class LangOC {
    var ref: LangSwift? = nil
    var name: String
    init(name: String) {
        self.name = name
    }
    
    deinit {
        print("OC 内存被释放了 -", self.name)
    }
}

class LangSwift {
    var ref: LangOC? = nil
    var name: String
    init(name: String) {
        self.name = name
    }
    
    deinit {
        print("Swift 内存被释放了 -", self.name)
    }
}

var obj1: LangOC? = LangOC(name: "Object-C")
var obj2: LangSwift? = LangSwift(name: "Swift")

// 循环引用 // LangOC 引用为2， LangSwift引用为2
obj1?.ref = obj2
obj2?.ref = obj1

// 想要释放 obj1
//obj1 = nil // LangOC 被没有被释放
// 解决循环引用？ 3个步骤
obj1?.ref = nil // LangOC 引用为2, LangSwift 引用为1
obj1 = nil // LangOC 引用为1, LangSwift 引用为1
obj2?.ref = nil // LangOC 引用为0, LangSwift 引用为1



/**
 --------------------------------------------------------------------
    目前 obj1 被 obj2一个进行了强引用，就需要3个步骤去 释放引用，如果多个呢？
 
    weak : 不会对 ARC 进行引用计数机制
*/

class LangLua {
    weak var ref: LangJava? = nil
    var name: String
    init(name: String) {
        self.name = name
    }
    
    deinit {
        print("LangLua 内存被释放了 -", self.name)
    }
}

class LangJava {
    weak var ref: LangLua? = nil
    var name: String
    init(name: String) {
        self.name = name
    }
    
    deinit {
        print("LangJava 内存被释放了 -", self.name)
    }
}

var obj3: LangLua? = LangLua(name: "Lua")
var obj4: LangJava? = LangJava(name: "Java")

obj3?.ref = obj4
obj4?.ref = obj3

obj3 = nil
obj4 = nil
